let fs = require("fs");

function delFile(p) {
    try {
        if (fs.statSync(p).isFile()) {
            fs.unlinkSync(p);
            return true;
        }
        if (fs.existsSync(p)) {
            let list = fs.readdirSync(p);
            list.forEach((v, i) => {
                let path = `${p}/${v}`, stats = fs.statSync(path);
                if (stats.isFile()) {
                    fs.unlinkSync(path);
                }
                else {
                    delFile(path);
                }
            });
            fs.rmdirSync(p);
            return true;
        }
    }
    catch (_) {
        return false;
    }
}



function main() {
    delFile("./index.txt");
    let str = "TMBotPluginIndex";
    fs.readdirSync("./plugins").forEach((v) => {
        try {
            let file = fs.readFileSync(`./plugins/${v}`);
            let obj = JSON.parse(file);
            if (v.indexOf(obj.name) != 0) {
                throw new Error(`插件名称与文件名不符!`);
            }
            str == "" ? str = v : (str += "\n" + v);
        } catch (e) {
            console.error(`Error in build "${v}" index`);
            console.error(e);
        }
    });
    fs.writeFileSync("./index.txt", str);
}

main();